import { Message } from 'element-ui'
import JSEncrypt from 'jsencrypt'

/**
 * 
 * @param  dataurl {base64}
 * @param  filename 
 * @returns 
 * base64转存文件
 */
function dataURLtoFile(dataurl, filename) { 
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}

/**
 * RC4加密
 */
export const Encrypt = (data, key) => {
    let encrypted = Encrypto.RC4.encrypt(data, key, {
        mode: Encrypto.mode.CTR,
    }).toString();
    return encrypted
}

/**
 * RC4解密
 */

export const Decrypt = (data, key) => {
    let decrypted = Encrypto.RC4.decrypt(data, key, {
        mode: Encrypto.mode.CTR,
    // });
    }).toString(Encrypto.enc.Utf8);
    return decrypted
}
/**
 * 加密文件
 */
export const EncryptFile = (file, key) => {
    return new Promise((resolve, reject) => {
        try {
            var file_mime = file.type;
            var file_name = file.name;
            const filename = `encrypt_${file_name}`;
            let reader = new FileReader();
            reader.onload = () => {
                const [type, data] = reader.result.split(',');
                let encrypted = Encrypto.RC4.encrypt(data, key, {
                    mode: Encrypto.mode.CTR,
                }).toString();
                var file2 = new File([`${type},${encrypted}`], filename,{
                    type: file_mime,
                });
                resolve(file2)
            };
            reader.readAsDataURL(file);
        }catch(e) {
            Message({
                type: 'error',
                message: '文件类型不正确'
            })
            reject(e)
        }
    })
}

/**
 * 解密文件
 */

export const DecryptFile = (file_name, file, key) => {
    return new Promise((resolve, reject) => {
        try {
            const [type, data] = file.split(',');
            let decrypted = Encrypto.RC4.decrypt(data, key, {
                mode: Encrypto.mode.CTR,
            // });
            }).toString(Encrypto.enc.Utf8);
            const filename = `decrypt_${file_name}`;
            var file2 = dataURLtoFile(`${type},${decrypted}`, filename);
            resolve(file2)
        } catch(e) {
            Message({
                type: 'error',
                message: '文件类型不正确'
            })
            reject(e)
        }
    })
}

/**
 * Rsa加密
 */

export const EncryptRsa = (data, key) => {
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(key);
    const encrypted = encrypt.encrypt(data);
    return encrypted
}

/**
 * Rsa解密
 */

export const DecryptRsa = (data, key) => {
    const decrypt = new JSEncrypt();
    decrypt.setPrivateKey(key);
    const decrypted = decrypt.decrypt(data);
    return decrypted
}